package com.kws.auth.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.kws.auth.form.LoginMessageBody;
import com.kws.auth.form.RegisterUserBody;
import com.kws.common.core.enums.ChannelEnum;
import com.kws.common.core.utils.HttpClientUtil;
import com.kws.system.api.domain.QueryAccessTokenInfo;
import com.kws.system.api.domain.QuerySmallProgramTokenInfo;
import com.kws.system.api.domain.Rq.QueryWeixinUserInfoRq;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.kws.common.core.constant.CacheConstants;
import com.kws.common.core.constant.Constants;
import com.kws.common.core.constant.SecurityConstants;
import com.kws.common.core.constant.UserConstants;
import com.kws.common.core.domain.R;
import com.kws.common.core.enums.UserStatus;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.core.text.Convert;
import com.kws.common.core.utils.DateUtils;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.core.utils.ip.IpUtils;
import com.kws.common.redis.service.RedisService;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.RemoteUserService;
import com.kws.system.api.domain.SysUser;
import com.kws.system.api.model.LoginUser;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author zhangyh
 */
@Component
public class SysLoginService
{
    private static final Logger logger = LoggerFactory.getLogger(SysLoginService.class);

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    // 微信登陆appid
    private static final String APPID = "wxe0530f906027957a";

    // 微信登陆key
    private static final String SECRET_KEY = "be2187e9ebd1a04b5fd415e1f37a03be";


    // 商家微信登陆appid
    private static final String SMALL_PROGRAM_APP_ID = "wx6e0aa65f315c7160";

    // 商家微信登陆key
    private static final String SMALL_PROGRAM_APP_KEY = "aab60877b16be9ece0cf62c222002f10";

    //用户小程序登陆appid
    private static final String MERCHANT_MIN_APP_ID = "wxd862c8568f4fd046";

    //用户小程序登陆AppSecret
    private static final String MERCHANT_MIN_APP_KEY = "2855f24d3ba98fad0ed8f15004002ee1";

    /**
     * 获取小程序登陆信息
     */
    private static final String SMALL_PROGRAM_URL = "https://api.weixin.qq.com/sns/jscode2session";


    // 获取微信登陆code地址
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";

    private static final String REFRESH_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token";

    // 校验刷新accessToken是否有效地址
    private static final String CHECK_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/auth";



    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        // 更新用户登录IP
        sysUser.setLoginIp(IpUtils.getIpAddr());
        // 更新用户登录时间
        sysUser.setLoginDate(DateUtils.getNowDate());
        remoteUserService.recordUserLogin(sysUser, SecurityConstants.INNER);
    }

    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    public LoginUser smallProgramLogin(String code,String channel) {
        Map<String, String> requestUrlParam = new HashMap<>();
        if (channel.equals(ChannelEnum.CHANNEL_MERCHANT_MIN.getKey())){
            requestUrlParam.put("appid",SMALL_PROGRAM_APP_ID);
            requestUrlParam.put("secret",SMALL_PROGRAM_APP_KEY);
        }else if (channel.equals(ChannelEnum.CHANNEL_USER_MIN.getKey())){
            requestUrlParam.put("appid",MERCHANT_MIN_APP_ID);
            requestUrlParam.put("secret",MERCHANT_MIN_APP_KEY);
        }

        requestUrlParam.put("js_code",code);
        requestUrlParam.put("grant_type","authorization_code");
        String respon = HttpClientUtil.doGet(SMALL_PROGRAM_URL,requestUrlParam);
        logger.info("调用小程序获取用户openId返回结果:{}"+respon);
        if (StringUtils.isNotEmpty(respon)){
            QuerySmallProgramTokenInfo smallProgramTokenInfo = JSONUtil.toBean(respon, QuerySmallProgramTokenInfo.class);
            if (StringUtils.isNotEmpty(smallProgramTokenInfo.getErrcode())){
                throw  new ServiceException("微信小程序授权失败！");
            }
            QueryAccessTokenInfo info = new QueryAccessTokenInfo();
            info.setOpenid(smallProgramTokenInfo.getOpenid());
            info.setUnionid(smallProgramTokenInfo.getUnionid());
            info.setChannel(channel);
            R<LoginUser> userResult = remoteUserService.checkUserByAppCode(info, SecurityConstants.INNER);
            if (R.FAIL == userResult.getCode())
            {
                throw new ServiceException(userResult.getMsg());
            }
            LoginUser userInfo = userResult.getData();
            if (null == userResult.getData().getSysUser()){
                userInfo.setOpenId(info.getOpenid());
                return userInfo;
            }
            SysUser user = userResult.getData().getSysUser();
            if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
            {
                recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
                throw new ServiceException("对不起，您的账号："  + " 已被删除");
            }
            if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
            {
                recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
                throw new ServiceException("对不起，您的账号："  + " 已停用");
            }

            recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_SUCCESS, "登录成功");
            recordLoginInfo(user.getUserId());
            return userInfo;
        }else {
            throw new ServiceException("微信授权登陆失败，请重试！");
        }
    }


    private String getUserPhoneNumber(String sessionKey, String iv, String encryptedData) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec keySpec = new SecretKeySpec(Base64.getDecoder().decode(sessionKey), "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(Base64.getDecoder().decode(iv)));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, parameters);

            byte[] result = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            String phoneNumberJsonStr = new String(result, StandardCharsets.UTF_8);
            JSONObject phoneNumberJson = JSONObject.parseObject(phoneNumberJsonStr);
            return phoneNumberJson.getString("purePhoneNumber");
        } catch (Exception e) {
            logger.error("微信用户手机号解密异常，sessionKey:{}, encryptedData:{}, iv:{}, 错误信息:{}", sessionKey, encryptedData, iv, e.getMessage());
            return null;
        }
    }


    public LoginUser weiXinLogin(String code, String channel) {
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid",APPID);
        requestUrlParam.put("secret",SECRET_KEY);
        requestUrlParam.put("code",code);
        requestUrlParam.put("grant_type","authorization_code");
        String respon = HttpClientUtil.doGet(ACCESS_TOKEN_URL,requestUrlParam);
        logger.info("调用腾讯获取access_token返回结果:{}"+respon);

        if (StringUtils.isNotEmpty(respon)){
            QueryAccessTokenInfo info = JSONUtil.toBean(respon, QueryAccessTokenInfo.class);
            info.setChannel(channel);
            R<LoginUser> userResult = remoteUserService.checkUserByAppCode(info, SecurityConstants.INNER);
            if (R.FAIL == userResult.getCode())
            {
                throw new ServiceException(userResult.getMsg());
            }

            LoginUser userInfo = userResult.getData();
            SysUser user = userResult.getData().getSysUser();
            if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
            {
                recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
                throw new ServiceException("对不起，您的账号："  + " 已被删除");
            }
            if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
            {
                recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
                throw new ServiceException("对不起，您的账号："  + " 已停用");
            }
            recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_SUCCESS, "登录成功");
            recordLoginInfo(user.getUserId());
            return userInfo;
        }else {
            throw new ServiceException("微信授权登陆失败，请重试！");
        }
    }

    public LoginUser messageLogin(LoginMessageBody from) {
        R<LoginUser> userResult = remoteUserService.checkUserByUserPhone(from.getPhone(), SecurityConstants.INNER);
        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号："  + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号："  + " 已停用");
        }
        if (StringUtils.isEmpty(from.getMessageCode())){
            recordLogService.recordLogininfor("用户登陆", Constants.LOGIN_FAIL, "验证码信息不能为空");
            throw new ServiceException("对不起，验证码信息不能为空");
        }else {
            String messageCode = redisService.getCacheObject(from.getPhone());
            if (!from.getMessageCode().equals(messageCode)){
                recordLogService.recordLogininfor("用户登陆", Constants.LOGIN_FAIL, "验证码信息错误");
                throw new ServiceException("对不起，验证码信息错误！");
            }
        }
        recordLogService.recordLogininfor("用户登陆", Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }

    public R registerUserUser(RegisterUserBody body) {
        R status = remoteUserService.registerUserUser(body.getPhone(), body.getUserType(),body.getPassword(), SecurityConstants.INNER);
        if (R.FAIL == status.getCode())
        {
            throw new ServiceException(status.getMsg());
        }
        if (StringUtils.isEmpty(body.getMessageCode())){
            return R.fail("短信验证码不能为空");
        }
        String messageCode = redisService.getCacheObject(body.getPhone());
        if (StringUtils.isNotEmpty(messageCode) && body.getMessageCode().equals(messageCode)){
            return R.ok();
        }else {
            return R.fail("验证码不正确！");
        }
    }

    public LoginUser bindUserOpenId(String openId, String phone,String channel) {
        R<LoginUser> userResult = remoteUserService.bindUserOpenId(openId,phone,channel, SecurityConstants.INNER);
        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号："  + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号："  + " 已停用");
        }

        recordLogService.recordLogininfor("微信登陆", Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }
}
